package com.szmmsoft.mp.common.aspect;


import com.szmmsoft.mp.common.anno.Sign;
import com.szmmsoft.mp.common.constant.Constants;
import com.szmmsoft.mp.common.model.R;
import com.szmmsoft.mp.common.until.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;

import java.lang.reflect.Method;

import java.util.Date;
import java.util.Objects;

/**
 * 判断是否签名，补充requestID,补充时间
 *
 * @author ethan
 * @version 1.0.0
 * @since 2024-10-14
 */
@Component
@Aspect
@Slf4j
public class ReqAspect {

    @Pointcut("execution (* com.szmmsoft.*.controller.*.*(..))")
    void reqPointCut(){

    }

    @Around("reqPointCut()")
    Object arountAdvice(ProceedingJoinPoint process) throws Throwable {
        MethodSignature signature = (MethodSignature) process.getSignature();
        Method method = signature.getMethod();
        //签名校验
        if (method.isAnnotationPresent(Sign.class)) {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            SignUtil.checkSign(request);
        }
        Object[] args = process.getArgs();
        Object object = process.proceed(args);
        if (object instanceof R){
            R result = (R) object;
            result.setRequestId(MDC.get(Constants.REQ_ID));
            result.setTime(new Date());
            return result;
        }
        return object;
    }



}
